//
//  OnlineTabBar.m
//  iBaby365v2
//
//  Created by admin on 14/12/2.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "OnlineTabBar.h"
#import "OnlineTabBarButton.h"

@interface OnlineTabBar()
/**
 *  记录当前选中的按钮
 */
@property (nonatomic,weak) OnlineTabBarButton *selectedButton;
@end

@implementation OnlineTabBar

-(void)addTabButtonWithName:(NSString *)name selName:(NSString *)selName titleName:(NSString *)titleName
{
    //创建按钮
    OnlineTabBarButton *button = [OnlineTabBarButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:titleName forState:UIControlStateNormal];
    //设置图片
    [button setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:selName] forState:UIControlStateSelected];
    //添加
    [self addSubview:button];
    
    //监听
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    //默认选中第0个按钮
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
}
-(void) layoutSubviews
{
    [super layoutSubviews];
    int count = self.subviews.count;
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width/count;
    CGFloat buttonH = self.frame.size.height;
    
    for (int i=0; i<count; i++) {
        OnlineTabBarButton *button = self.subviews[i];
       
        //设置frame
        CGFloat buttonX = i*buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        button.tag = i;
    }
}
/**
 *  监听按钮点击
 */
-(void)buttonClick:(OnlineTabBarButton *)button
{
//    通知代理
//    判断代理是否实现代理方法
    if([self.delegate respondsToSelector:@selector(tabBar:didselectButtonFrom:to:)])
    {
        [self.delegate tabBar:self didselectButtonFrom:self.selectedButton.tag to:button.tag];
    }
    self.selectedButton.selected = NO;
    button.selected =YES;
    self.selectedButton = button;
}
@end
